package com.aion.jirc.irc;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;

/**
 * Created by IntelliJ IDEA.
 * Date: 11-02-16
 * Time: 19:47
 *
 * @author Aion
 * @author Zippy
 */
public class InputHandler extends Thread {

    private final BufferedReader br;
    private final LinkedList<String> messages;

    private final Object eventMonitor;

    /**
     * Initializes the input handler.
     *
     * @param br
     *          the <code>BufferedReader</code> instance
     * @param eventMonitor
     *          the <code>Object</code>
     * @throws Exception
     *          caught exceptions
     */
    protected InputHandler(BufferedReader br, Object eventMonitor) throws Exception {
        super("Input handler");
        if (br == null || eventMonitor == null) {
            throw new InstantiationError("Arguments are null");
        }
        messages = new LinkedList<String>();
        this.br = br;
        this.eventMonitor = eventMonitor;
    }

    /**
     * Gets the first pending message.
     *
     * @return the first pending message
     */
    public String getPendingMessage() {
        synchronized (messages) {
            return messages.removeFirst();
        }
    }

    /**
     * Checks whether or not there is/are message(s) pending.
     *
     * @return <tt>true</tt> if there is at least one message pending; otherwise <tt>false</tt>
     */
    public boolean hasPendingMessage() {
        synchronized (messages) {
            return !messages.isEmpty();
        }
    }

    public void run() {
        try {
            while (true) {
                String input = br.readLine();
                if (input == null) {
                    System.out.println("Died...");
                    break;
                }
                synchronized (messages) {
                    messages.addLast(input);
                }
                synchronized (eventMonitor) {
                    eventMonitor.notifyAll();
                }
            }
        } catch (Exception e) { }
    }
}
